package com.ncloud.timetask.business;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.timetask.dao.BaseDao;
import com.ncloud.timetask.utils.LatAndLngByBaiduUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Types;
import java.util.List;
import java.util.Map;

/**
 * Created by shiqiang on 2017/7/13.
 */
@Component
public class LatAndLngBusi {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private BaseDao baseDao;
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void excute(){
        StringBuffer sql = new StringBuffer("select a.node_id ,a.eqpt_id ,b.county_name as city ,a.uses_address as address from bs_eqpt_info a,bs_p_county_info b ");
        sql.append(" where a.city = b.county_id and b.level='2' and  a.begin_date >= date_sub(now(),interval 1 day) and a.remark is null limit 100 for update");

        List<Map<String,Object>> list = baseDao.commonQuery(sql.toString());
        list.stream().forEach(map ->{
            //logger.info("eqpt_id="+map.get("eqpt_id")+";city="+map.get("city"));
            Long eqptId= Long.parseLong(map.get("eqpt_id").toString());
            String city = map.get("city").toString();
            String address = map.get("address").toString();
            address = city+address;
            if(!StringUtils.isEmpty(address)){
                JSONObject info =  LatAndLngByBaiduUtil.getLngAndLat(city,address);
                if("0".equals(info.getString("status"))){
                    //update eqpt info
                    String updateSql=" update bs_eqpt_info set longitude=?,latitude=? ,remark =? where eqpt_id=?   and now() BETWEEN begin_date and end_date ";
                    int num = baseDao.update(updateSql,new Object[]{info.getDouble("lng"),info.getDouble("lat"),"1",eqptId},
                            new int[]{Types.DECIMAL,Types.DECIMAL,Types.VARCHAR,Types.BIGINT});
                }else{
                    //update error info
                    String updateSql=" update bs_eqpt_info set remark =? where eqpt_id=?   and now() BETWEEN begin_date and end_date ";
                    int num = baseDao.update(updateSql,new Object[]{info.getString("msg"),eqptId},
                            new int[]{Types.VARCHAR,Types.BIGINT});
                }
                logger.info(info.toJSONString());
            }
        });
    }
}
